package concurrency;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class Philosopher implements Runnable {
    private Chopstick mLeft;

    private Chopstick mRight;

    private final int mId;

    private final int mPonderFactor;

    private Random mRand = new Random(47);

    public Philosopher(Chopstick left, Chopstick right, int id, int ponder) {
        mLeft = left;
        mRight = right;
        mId = id;
        mPonderFactor = ponder;
    }

    private void pause() throws InterruptedException {
        if(mPonderFactor == 0) {
            return;
        }

        int timeOut = mRand.nextInt(mPonderFactor * 250);
        TimeUnit.MILLISECONDS.sleep(timeOut);
    }

    @Override
    public String toString() {
        return "Philosopher " + mId;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(this + " thinking");
                pause();
                // Philosopher becomes hungry
                System.out.println(this + " grabbing right");
                mRight.take();
                System.out.println(this + " grabbing left");
                mLeft.take();
                System.out.println(this + " eating");
                pause();
                mRight.drop();
                mLeft.drop();
            }
        } catch (InterruptedException e) {
            System.out.println(this + " exiting via interrupt");
        }
    }
}
